package api

import (
	"github.com/gin-gonic/gin"

	"gitee.com/dn-jinmin/chatcms/internal/domain"
	"gitee.com/dn-jinmin/chatcms/internal/logic"
	"gitee.com/dn-jinmin/chatcms/internal/svc"
	"gitee.com/dn-jinmin/chatcms/pkg/httpx"
)

type Speechcraft struct {
	svcCtx      *svc.ServiceContext
	speechcraft logic.Speechcraft
}

func NewSpeechcraft(svcCtx *svc.ServiceContext, speechcraft logic.Speechcraft) *Speechcraft {
	return &Speechcraft{
		svcCtx:      svcCtx,
		speechcraft: speechcraft,
	}
}

func (h *Speechcraft) InitRegister(engine *gin.Engine) {
	g := engine.Group("v1/speechcraft")
	g.GET("", h.List)
	g.GET("/:id", h.Info)
	g.POST("", h.Create)
	g.PUT("/:id", h.Edit)
	g.DELETE("/:id", h.Delete)
}

func (h *Speechcraft) List(ctx *gin.Context) {
	var req domain.SpeechcraftListReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.speechcraft.List(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

func (h *Speechcraft) Info(ctx *gin.Context) {
	var req domain.IdReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.speechcraft.Info(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

func (h *Speechcraft) Create(ctx *gin.Context) {
	var req domain.Speechcraft
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	err := h.speechcraft.Create(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.Ok(ctx)
	}
}

func (h *Speechcraft) Edit(ctx *gin.Context) {
	var req domain.Speechcraft
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	err := h.speechcraft.Edit(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.Ok(ctx)
	}
}

func (h *Speechcraft) Delete(ctx *gin.Context) {
	var req domain.IdReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	err := h.speechcraft.Delete(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.Ok(ctx)
	}
}
